import React, {
  Children,
  ReactNode,
  useCallback,
  useEffect,
  useRef,
  useState,
} from 'react';
import {
  View,
  TouchableOpacity,
  StyleSheet,
  Pressable,
  ViewStyle,
  Text,
  useWindowDimensions,
  Platform,
} from 'react-native';
import { RouteProp, useNavigation, useRoute } from '@react-navigation/native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useHeaderHeight } from '@react-navigation/elements';
import { Button, Tag, useAppTheme } from 'tsun-smart-ui';
import { Icon } from 'tsun-smart-ui';
import { useTranslation } from 'react-i18next';
import { stationApi, StationDTO } from '@/services/api/stationApi';
import StationSummary from './StationSummary';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { useDispatch, useSelector } from 'react-redux';
import { RootState } from '@/store';
import {
  setCurrentStation,
  setStationList,
} from '@/store/slices/fullSceneSlice';
import { colorScheme } from 'nativewind';
import { useNativePopover } from '@/hooks/usePopover';
import { useMMKVNumber, useMMKVString } from '@/hooks/useMMkv';

let targetStationId: string | number | null = null;

const Summary: React.FC = () => {
  const { t } = useTranslation();
  const navigation = useNavigation<NativeStackNavigationProp<any>>();
  const route = useRoute<RouteProp<any>>();
  const [leftMenuVisible, setLeftMenuVisible] = useState(false);
  const [rightMenuVisible, setRightMenuVisible] = useState(false);
  const dispatch = useDispatch();
  const stations = useSelector<RootState, StationDTO[]>(
    (state) => state.fullScene.stationList
  );
  const currentStation = useSelector<RootState, StationDTO | null>(
    (state) => state.fullScene.currentStation
  );
  const tapCount = useRef(0);
  const [showRightPopover, rightAnchorRef] = useNativePopover();
  const [showLeftPopover, leftAnchorRef] = useNativePopover();
  const [lastSelectedStationId, setLastSelectedStationId] = useMMKVString(
    'lastSelectedStationId'
  );

  const appTheme = useAppTheme();

  useEffect(() => {
    const unsubscribe = navigation.addListener('focus', () => {
      reloadStations();
    });
    return unsubscribe;
  }, [currentStation]);

  useEffect(() => {
    if (route?.params?.newStationId) {
      targetStationId = route?.params?.newStationId;
    }
  }, [route?.params?.newStationId]);

  useEffect(() => {
    const popoverBackgroundColor =
      appTheme.colors?.background?.primary ?? '#fff';
    const popoverTextColor = appTheme.colors?.neutral?.title ?? '#000';
    const separatorColor = appTheme.colors?.border?.primary ?? '#CCC';
    const showLeftMenu = stations.length > 0;
    const leftMenu = showLeftMenu ? (
      <TouchableOpacity
        className="flex-row items-center mx-3 gap-1"
        ref={leftAnchorRef}
        onPress={async () => {
          let stationNames: string[] = [];
          let selectedIndex = 0;
          stations.forEach((station, index) => {
            stationNames.push(station.stationName);
            if (station.id === currentStation?.id) {
              selectedIndex = index;
            }
          });

          const index = await showLeftPopover(stationNames, selectedIndex, {
            menuWidth: 180,
            shadowColor: '#CCC',
            backgroundColor: popoverBackgroundColor,
            textColor: popoverTextColor,
            separatorColor: separatorColor,
          });
          if (index != null) {
            const station = stations[index];
            setLastSelectedStationId(`${station.id}`);
            dispatch(setCurrentStation(station));
          }
        }}
      >
        <Text className="light text-text1 text-[17px] font-semibold">
          {currentStation?.stationName}
        </Text>
        <Icon name="pull" size={16} color={appTheme.colors?.neutral?.title} />
      </TouchableOpacity>
    ) : null;
    let showManagementButton = stations.length > 0;
    let showAddButton = stations.length > 0;
    let addMenuOptions = [
      t('sys.app.station.create', { defaultValue: '新建电站' }),
      t('common.add.device', { defaultValue: '添加设备' }),
    ];
    const rightMenuView = (
      <View className="items-center flex-row px-3 gap-3">
        {showManagementButton && (
          <TouchableOpacity
            onPress={() => navigation.navigate('OwnerStationList')}
          >
            <Icon
              name="management"
              size={25}
              color={appTheme.colors?.neutral?.title}
            />
          </TouchableOpacity>
        )}
        {showAddButton && (
          <TouchableOpacity
            ref={rightAnchorRef}
            onPress={async () => {
              const index = await showRightPopover(addMenuOptions, null, {
                menuWidth: 160,
                backgroundColor: popoverBackgroundColor,
                textColor: popoverTextColor,
                separatorColor: separatorColor,
              });
              if (index === 0) {
                navigation.navigate('CreatePowerStation');
              } else if (index === 1) {
                navigation.navigate('SelectDeviceCategory', {
                  station: currentStation,
                });
              }
            }}
          >
            <Icon
              name="add"
              size={26}
              color={appTheme.colors?.neutral?.title}
            />
          </TouchableOpacity>
        )}
      </View>
    );

    navigation.setOptions({
      headerLeft: () => leftMenu,
      headerTitle: () => (
        <TouchableOpacity
          className="w-5 h-10"
          onPress={() => {
            tapCount.current += 1;
            if (tapCount.current >= 10) {
              tapCount.current = 0;
              navigation.navigate('Debugging');
            }
          }}
        />
      ),
      headerRight: () => rightMenuView,
    });
  }, [
    navigation,
    leftMenuVisible,
    rightMenuVisible,
    stations,
    currentStation,
    colorScheme,
    appTheme,
    t,
    lastSelectedStationId,
  ]);

  const reloadStations = useCallback(() => {
    stationApi.getUserStations().then((res) => {
      if (res.data.records) {
        if (lastSelectedStationId && !currentStation) {
          let newStation = res.data.records.find(
            (station) => `${station.id}` == lastSelectedStationId
          );
          if (newStation) {
            dispatch(setCurrentStation(newStation));
          }
        }
        dispatch(setStationList(res.data.records));
        if (targetStationId != null) {
          let newStation = res.data.records.find(
            (station) => station?.id == targetStationId
          );
          if (newStation) {
            dispatch(setCurrentStation(newStation));
            targetStationId = null;
          }
        }
      }
    });
  }, [lastSelectedStationId, currentStation]);

  return (
    <StationSummary
      station={currentStation}
      key={currentStation?.id}
    />
  );
};

export default React.memo(Summary);
